package com.wuyan.web.base.helper;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射工具类
 *
 * @author wuyan
 */

public class ReflexHelper {

    private ReflexHelper() {
    }

    /**
     * 获取指定字段的值
     *
     * @param obj       实例
     * @param fieldName 字段名
     * @param clz       字段类类型
     * @return T
     * @throws IllegalAccessException    无访问权限
     * @throws NoSuchMethodException     不存在此方法
     * @throws InvocationTargetException 调用方法时错误
     */
    public static <T> T getFieldValue(Object obj, String fieldName, Class<T> clz)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String capitalize = StringUtils.capitalize(fieldName);
        Method method = obj.getClass().getMethod("get" + capitalize);
        Object value = method.invoke(obj);
        return clz.cast(value);
    }

    /**
     * 设置指定字段的值
     *
     * @param obj       实例
     * @param fieldName 字段名
     * @param value     值
     * @throws IllegalAccessException    无访问权限
     * @throws NoSuchMethodException     不存在此方法
     * @throws InvocationTargetException 调用方法时错误
     */
    public static void setFieldValue(Object obj, String fieldName, Object value)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String capitalize = StringUtils.capitalize(fieldName);
        Method method = obj.getClass().getMethod("set" + capitalize, value.getClass());
        method.invoke(obj, value);
    }
}
